import os
import time
from flask import Blueprint, jsonify, request, send_file, abort, current_app
from werkzeug.exceptions import NotFound

from app.services import directory_scanner, image_processor, cache_manager
from app.utils import is_subdirectory, url_safe_path

api_bp = Blueprint('api', __name__)

@api_bp.route('/comics')
def get_comics():
    """获取漫画列表API"""
    try:
        page = request.args.get('page', 1, type=int)
        limit = request.args.get('limit', 20, type=int)
        search = request.args.get('search', '', type=str)
        
        if search:
            comics = directory_scanner.comic_library.search_comics(search)
            total = len(comics)
            # 手动分页
            start = (page - 1) * limit
            end = start + limit
            comics = comics[start:end]
        else:
            comics, total = directory_scanner.comic_library.get_comics(page, limit)
        
        # 转换为摘要格式
        comic_data = [comic.to_summary_dict() for comic in comics]
        
        return jsonify({
            'status': 'success',
            'data': {
                'comics': comic_data,
                'pagination': {
                    'page': page,
                    'limit': limit,
                    'total': total,
                    'total_pages': (total + limit - 1) // limit
                }
            }
        })
        
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@api_bp.route('/comics/<comic_id>')
def get_comic(comic_id):
    """获取漫画详情API"""
    try:
        comic = directory_scanner.comic_library.get_comic(comic_id)
        if not comic:
            return jsonify({
                'status': 'error',
                'message': '漫画不存在'
            }), 404
        
        return jsonify({
            'status': 'success',
            'data': comic.to_dict()
        })
        
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@api_bp.route('/comics/<comic_id>/chapters')
def get_chapters(comic_id):
    """获取章节列表API"""
    try:
        comic = directory_scanner.comic_library.get_comic(comic_id)
        if not comic:
            return jsonify({
                'status': 'error',
                'message': '漫画不存在'
            }), 404
        
        chapters_data = [chapter.to_dict() for chapter in comic.chapters]
        
        return jsonify({
            'status': 'success',
            'data': {
                'comic_id': comic_id,
                'chapters': chapters_data
            }
        })
        
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@api_bp.route('/chapters/<chapter_id>/pages')
def get_pages(chapter_id):
    """获取页面列表API"""
    try:
        # 查找章节
        chapter = None
        comic = None
        
        for c in directory_scanner.comic_library.comics:
            for ch in c.chapters:
                if ch.id == chapter_id:
                    chapter = ch
                    comic = c
                    break
            if chapter:
                break
        
        if not chapter:
            return jsonify({
                'status': 'error',
                'message': '章节不存在'
            }), 404
        
        pages_data = [page.to_dict() for page in chapter.pages]
        
        # 为每个页面生成图片URL
        for page_data in pages_data:
            page_data['image_url'] = f"/api/image/{url_safe_path(page_data['image_path'])}"
            page_data['thumbnail_url'] = f"/api/thumbnail/{url_safe_path(page_data['image_path'])}"
        
        return jsonify({
            'status': 'success',
            'data': {
                'chapter_id': chapter_id,
                'comic_id': comic.id,
                'pages': pages_data
            }
        })
        
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@api_bp.route('/image/<path:image_path>')
def get_image(image_path):
    """获取图片资源API"""
    try:
        # URL解码路径
        from urllib.parse import unquote
        image_path = unquote(image_path)
        
        # 安全检查：确保路径在允许的目录内
        comic_path = current_app.config.get('COMIC_PATH', '')
        if not is_subdirectory(image_path, comic_path):
            abort(403)
        
        # 检查文件是否存在
        if not os.path.exists(image_path):
            abort(404)
        
        # 获取处理参数
        quality = request.args.get('quality', type=int)
        width = request.args.get('width', type=int)
        height = request.args.get('height', type=int)
        
        max_size = None
        if width and height:
            max_size = (width, height)
        elif width:
            max_size = (width, 9999)
        elif height:
            max_size = (9999, height)
        
        # 生成缓存键
        cache_key = cache_manager.generate_cache_key(
            'image', image_path, quality or 85, max_size or 'original'
        )
        
        # 检查缓存
        cached_path = cache_manager.get_from_cache(cache_key)
        if cached_path and os.path.exists(cached_path):
            return send_file(cached_path, mimetype='image/jpeg')
        
        # 处理图片
        processed_path = image_processor.process_image(image_path, quality, max_size)
        if not processed_path:
            # 如果处理失败，返回原始文件
            return send_file(image_path)
        
        # 添加到缓存
        cache_manager.add_to_cache(cache_key, processed_path, {
            'original_path': image_path,
            'quality': quality,
            'max_size': max_size
        })
        
        return send_file(processed_path, mimetype='image/jpeg')
        
    except Exception as e:
        current_app.logger.error(f'获取图片失败 {image_path}: {e}')
        abort(500)

@api_bp.route('/thumbnail/<path:image_path>')
def get_thumbnail(image_path):
    """获取缩略图API"""
    try:
        # URL解码路径
        from urllib.parse import unquote
        image_path = unquote(image_path)
        
        # 安全检查
        comic_path = current_app.config.get('COMIC_PATH', '')
        if not is_subdirectory(image_path, comic_path):
            abort(403)
        
        if not os.path.exists(image_path):
            abort(404)
        
        # 获取缩略图尺寸参数
        width = request.args.get('width', 300, type=int)
        height = request.args.get('height', 400, type=int)
        size = (width, height)
        
        # 生成缓存键
        cache_key = cache_manager.generate_cache_key(
            'thumbnail', image_path, f"{width}x{height}"
        )
        
        # 检查缓存
        cached_path = cache_manager.get_from_cache(cache_key)
        if cached_path and os.path.exists(cached_path):
            return send_file(cached_path, mimetype='image/jpeg')
        
        # 创建缩略图
        thumbnail_path = image_processor.create_thumbnail(image_path, size)
        if not thumbnail_path:
            # 如果创建失败，返回原始文件
            return send_file(image_path)
        
        # 添加到缓存
        cache_manager.add_to_cache(cache_key, thumbnail_path, {
            'original_path': image_path,
            'size': size,
            'type': 'thumbnail'
        })
        
        return send_file(thumbnail_path, mimetype='image/jpeg')
        
    except Exception as e:
        current_app.logger.error(f'获取缩略图失败 {image_path}: {e}')
        abort(500)

@api_bp.route('/cache/preload', methods=['POST'])
def preload_cache():
    """预加载图片API"""
    try:
        data = request.get_json()
        chapter_id = data.get('chapter_id')
        start_page = data.get('start_page', 1)
        page_count = data.get('page_count', 5)
        
        if not chapter_id:
            return jsonify({
                'status': 'error',
                'message': '缺少章节ID'
            }), 400
        
        # 查找章节
        chapter = None
        for comic in directory_scanner.comic_library.comics:
            for ch in comic.chapters:
                if ch.id == chapter_id:
                    chapter = ch
                    break
            if chapter:
                break
        
        if not chapter:
            return jsonify({
                'status': 'error',
                'message': '章节不存在'
            }), 404
        
        # 预加载页面
        preloaded_count = 0
        end_page = min(start_page + page_count, chapter.page_count)
        
        for page_num in range(start_page, end_page + 1):
            page = chapter.get_page(page_num)
            if page:
                # 预处理图片
                cache_key = cache_manager.generate_cache_key(
                    'image', page.image_path, 85, 'original'
                )
                
                if not cache_manager.is_cached(cache_key):
                    processed_path = image_processor.process_image(page.image_path)
                    if processed_path:
                        cache_manager.add_to_cache(cache_key, processed_path)
                        preloaded_count += 1
        
        return jsonify({
            'status': 'success',
            'data': {
                'preloaded_count': preloaded_count,
                'chapter_id': chapter_id,
                'start_page': start_page,
                'end_page': end_page
            }
        })
        
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@api_bp.route('/cache/clear', methods=['DELETE'])
def clear_cache():
    """清除缓存API"""
    try:
        cache_type = request.args.get('type', 'all')
        
        # 清除不同类型的缓存
        if cache_type in ('all', 'images'):
            image_processor.clear_cache('images')
        
        if cache_type in ('all', 'thumbnails'):
            image_processor.clear_cache('thumbnails')
        
        if cache_type in ('all', 'system'):
            cache_manager.clear_cache('all')
        
        return jsonify({
            'status': 'success',
            'message': f'{cache_type} 缓存已清除'
        })
        
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@api_bp.route('/stats')
def get_stats():
    """获取系统统计信息API"""
    try:
        library_stats = directory_scanner.get_library_stats()
        cache_stats = cache_manager.get_cache_stats()
        image_cache_stats = image_processor.get_cache_stats()
        
        return jsonify({
            'status': 'success',
            'data': {
                'library': library_stats,
                'cache': cache_stats,
                'image_cache': image_cache_stats
            }
        })
        
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@api_bp.route('/scan', methods=['POST'])
def scan_comics():
    """扫描漫画目录API"""
    try:
        force_refresh = request.args.get('force', False, type=bool)
        
        # 异步扫描（在实际应用中可能需要使用Celery等任务队列）
        directory_scanner.scan_comics(force_refresh=force_refresh)
        
        stats = directory_scanner.get_library_stats()
        
        return jsonify({
            'status': 'success',
            'message': '扫描完成',
            'data': stats
        })
        
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

@api_bp.route('/health')
def health_check():
    """健康检查API"""
    try:
        comic_path = current_app.config.get('COMIC_PATH', '')
        comic_path_exists = os.path.exists(comic_path)
        
        cache_dir = current_app.config.get('CACHE_DIR', '')
        cache_dir_exists = os.path.exists(cache_dir)
        
        return jsonify({
            'status': 'success',
            'data': {
                'service': 'Comic Reader API',
                'version': '1.0.0',
                'comic_path': comic_path,
                'comic_path_exists': comic_path_exists,
                'cache_dir': cache_dir,
                'cache_dir_exists': cache_dir_exists,
                'timestamp': int(time.time())
            }
        })
        
    except Exception as e:
        return jsonify({
            'status': 'error',
            'message': str(e)
        }), 500

# 错误处理
@api_bp.errorhandler(404)
def not_found(error):
    return jsonify({
        'status': 'error',
        'message': '资源不存在'
    }), 404

@api_bp.errorhandler(403)
def forbidden(error):
    return jsonify({
        'status': 'error',
        'message': '访问被拒绝'
    }), 403

@api_bp.errorhandler(500)
def internal_error(error):
    return jsonify({
        'status': 'error',
        'message': '服务器内部错误'
    }), 500